package com.it.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.it.constants.SystemConstants;
import com.it.domain.ResponseResult;
import com.it.domain.entity.TreeHole;
import com.it.domain.entity.User;
import com.it.domain.vo.TreeHoleListVo;
import com.it.domain.vo.TreeHoleVo;
import com.it.enums.AppHttpCodeEnum;
import com.it.mapper.TreeHoleMapper;
import com.it.mapper.UserMapper;
import com.it.service.TreeHoleService;
import com.it.utils.BeanCopyUtils;
import com.it.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * (TreeHole)表服务实现类
 *
 * @author makejava
 * @since 2024-08-14 16:14:28
 */
@Service("treeHoleService")
public class TreeHoleServiceImpl extends ServiceImpl<TreeHoleMapper, TreeHole> implements TreeHoleService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private TreeHoleMapper treeHoleMapper;

    @Override
    public ResponseResult addTreeHole(String content) {
        if (content != null) {
            this.save(TreeHole.builder().userId(SecurityUtils.getUserId()).content(content).build());
            return ResponseResult.okResult();
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.CONTENT_NOT_NULL);
    }

    @Override
    public ResponseResult getTreeHole() {
        List<TreeHole> treeHoles = treeHoleMapper.selectList(new LambdaQueryWrapper<TreeHole>().eq(TreeHole::getIsCheck, SystemConstants.IS_CHECK_YES));
        if (treeHoles.isEmpty()) return null;
        List<TreeHoleVo> treeHoleListVos = BeanCopyUtils.copyBeanList(treeHoles, TreeHoleVo.class);
        for (TreeHole treeHole : treeHoles) {
            User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getId, treeHole.getUserId()));
            if(user == null) continue;
            treeHoleListVos.stream().map(treeHoleVo -> {
                if (user.getId() == treeHoleVo.getUserId()) {
                    treeHoleVo.setNickname(user.getUserName());
                    treeHoleVo.setAvatar(user.getAvatar());
                }
                return treeHoleVo;
            }).collect(Collectors.toList());
        }
        return ResponseResult.okResult(treeHoleListVos);
    }
}

